/**
 * 性能监控面板组件
 * 用于开发环境中可视化展示性能数据
 */
const app = getApp();

Component({
  options: {
    addGlobalClass: true,
    styleIsolation: 'isolated'
  },
  
  properties: {
    // 是否显示面板
    show: {
      type: Boolean,
      value: false
    },
    
    // 是否显示详细信息
    showDetail: {
      type: Boolean,
      value: false
    },
    
    // 自动刷新间隔（毫秒），0表示不自动刷新
    refreshInterval: {
      type: Number,
      value: 3000
    }
  },
  
  data: {
    // 性能数据
    performanceData: null,
    
    // 警告信息
    warnings: [],
    
    // 选中的性能指标类型
    selectedMetricType: 'pageLoad',
    
    // 指标类型选项
    metricTypes: [
      { label: '页面加载', value: 'pageLoad' },
      { label: '数据获取', value: 'dataFetch' },
      { label: '渲染性能', value: 'render' },
      { label: 'API调用', value: 'apiCall' }
    ],
    
    // 当前指标统计数据
    currentMetricStats: null,
    
    // 定时器ID
    timerId: null,
    
    // 时间线数据
    timelineData: []
  },
  
  lifetimes: {
    attached() {
      // 启动自动刷新
      this._startAutoRefresh();
    },
    
    detached() {
      // 停止自动刷新
      this._stopAutoRefresh();
    }
  },
  
  observers: {
    'show': function(show) {
      if (show) {
        this.refreshData();
      }
    },
    
    'refreshInterval': function(interval) {
      this._stopAutoRefresh();
      if (interval > 0) {
        this._startAutoRefresh();
      }
    },
    
    'selectedMetricType': function(type) {
      this._updateMetricStats();
    }
  },
  
  methods: {
    /**
     * 刷新性能数据
     */
    refreshData() {
      if (!this.data.show) return;
      
      try {
        const performanceMonitor = app.getPerformanceMonitor();
        if (!performanceMonitor) return;
        
        const report = performanceMonitor.generateReport();
        
        this.setData({
          performanceData: report,
          warnings: report.warnings
        });
        
        // 更新当前选择的指标统计
        this._updateMetricStats();
        
        // 更新时间线数据
        this._updateTimelineData();
      } catch (e) {
        console.error('刷新性能数据失败', e);
      }
    },
    
    /**
     * 更新指标统计数据
     * @private
     */
    _updateMetricStats() {
      if (!this.data.performanceData) return;
      
      const { summary } = this.data.performanceData;
      let stats = null;
      
      switch (this.data.selectedMetricType) {
        case 'pageLoad':
          stats = summary.pageLoadStats;
          break;
        case 'dataFetch':
          stats = summary.dataFetchStats;
          break;
        case 'render':
          stats = summary.renderStats;
          break;
        case 'apiCall':
          // 计算API调用的统计数据
          const apiCalls = Object.values(this.data.performanceData.measures)
            .filter(m => m.name.startsWith('API_'));
          
          if (apiCalls.length > 0) {
            const durations = apiCalls.map(m => m.duration);
            const sum = durations.reduce((a, b) => a + b, 0);
            stats = {
              avg: Math.round(sum / durations.length),
              max: Math.max(...durations),
              min: Math.min(...durations)
            };
          } else {
            stats = { avg: 0, max: 0, min: 0 };
          }
          break;
        default:
          stats = { avg: 0, max: 0, min: 0 };
      }
      
      this.setData({ currentMetricStats: stats });
    },
    
    /**
     * 更新时间线数据
     * @private
     */
    _updateTimelineData() {
      if (!this.data.performanceData) return;
      
      // 获取所有测量数据并按时间排序
      const measures = Object.values(this.data.performanceData.measures)
        .sort((a, b) => a.startTime - b.startTime);
      
      // 转换为时间线格式
      const timeline = measures.map(measure => ({
        id: measure.name,
        name: this._formatMeasureName(measure.name),
        startTime: measure.startTime,
        endTime: measure.endTime,
        duration: measure.duration,
        type: this._getMeasureType(measure.name)
      }));
      
      this.setData({ timelineData: timeline });
    },
    
    /**
     * 格式化测量名称
     * @param {String} name 原始名称
     * @returns {String} 格式化后的名称
     * @private
     */
    _formatMeasureName(name) {
      // 简化名称，去掉前缀
      return name
        .replace(/^(PAGE_LOAD_|RENDER_|API_)/, '')
        .replace(/_/g, ' ');
    },
    
    /**
     * 获取测量类型
     * @param {String} name 测量名称
     * @returns {String} 测量类型
     * @private
     */
    _getMeasureType(name) {
      if (name.startsWith('PAGE_LOAD_')) {
        return 'pageLoad';
      } else if (name.startsWith('RENDER_')) {
        return 'render';
      } else if (name.startsWith('API_')) {
        return 'apiCall';
      } else if (name.startsWith('DATA_FETCH_')) {
        return 'dataFetch';
      } else {
        return 'other';
      }
    },
    
    /**
     * 开始自动刷新
     * @private
     */
    _startAutoRefresh() {
      if (this.data.refreshInterval <= 0) return;
      
      this._stopAutoRefresh();
      
      this.data.timerId = setInterval(() => {
        this.refreshData();
      }, this.data.refreshInterval);
    },
    
    /**
     * 停止自动刷新
     * @private
     */
    _stopAutoRefresh() {
      if (this.data.timerId) {
        clearInterval(this.data.timerId);
        this.data.timerId = null;
      }
    },
    
    /**
     * 切换指标类型
     * @param {Object} e 事件对象
     */
    onChangeMetricType(e) {
      this.setData({
        selectedMetricType: e.currentTarget.dataset.type
      });
    },
    
    /**
     * 清除性能数据
     */
    onClearData() {
      try {
        const performanceMonitor = app.getPerformanceMonitor();
        if (performanceMonitor) {
          performanceMonitor.clearAll();
          this.refreshData();
        }
      } catch (e) {
        console.error('清除性能数据失败', e);
      }
    },
    
    /**
     * 切换详情显示
     */
    onToggleDetail() {
      this.setData({
        showDetail: !this.data.showDetail
      });
    },
    
    /**
     * 关闭面板
     */
    onClose() {
      this.triggerEvent('close');
    }
  }
}); 